package lib.android.timingbar.com.base.integration;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.view.View;
import lib.android.timingbar.com.base.mvp.EventMessage;
import lib.android.timingbar.com.base.util.BaseLog;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * AppManager
 * -----------------------------------------------------------------------------------------------------------------------------------
 * 对于产生的activity相关对象的堆栈管理
 *
 * @author rqmei on 2018/1/29
 */

public class AppManager {
    protected final String TAG = this.getClass ().getSimpleName ();
    public static final String IS_NOT_ADD_ACTIVITY_LIST = "is_add_activity_list";//是否加入到activity的list，管理
    public static final int START_ACTIVITY = 0;
    public static final int SHOW_SNACKBAR = 1;
    public static final int KILL_ALL = 2;
    public static final int APP_EXIT = 3;
    private Application mApplication;
    //管理所有activity
    public List<Activity> mActivityList;
    //当前在前台的activity
    private Activity mCurrentActivity;

    public AppManager(Application application) {
        this.mApplication = application;
        if (!EventBus.getDefault ().isRegistered (this))
            EventBus.getDefault ().register (this);
    }

    /**
     * 通过eventbus post事件,远程遥控执行对应方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(EventMessage message) {
        switch (message.getCode ()) {
            case START_ACTIVITY:
                if (message.getData () == null)
                    break;
                dispatchStart (message);
                break;
            case SHOW_SNACKBAR:
                if (message.getData () == null)
                    break;
                showSnackbar ((String) message.getData (), message.getCode () == 0 ? false : true);
                break;
            case KILL_ALL:
                killAll ();
                break;
            case APP_EXIT:
                appExit ();
                break;
            default:
                BaseLog.w (TAG, "The message.what not match");
                break;
        }
    }

    /**
     * 开启activity
     *
     * @param message
     */
    private void dispatchStart(EventMessage message) {
        if (message.getData () instanceof Intent)
            startActivity ((Intent) message.getData ());
        else if (message.getData () instanceof Class)
            startActivity ((Class) message.getData ());
    }

    /**
     * 使用snackbar显示内容
     *
     * @param message
     * @param isLong
     */
    public void showSnackbar(String message, boolean isLong) {
        if (getCurrentActivity () == null) {
            BaseLog.w (TAG, "mCurrentActivity == null when showSnackbar(String,boolean)");
            return;
        }
        View view = getCurrentActivity ().getWindow ().getDecorView ().findViewById (android.R.id.content);
        Snackbar.make (view, message, isLong ? Snackbar.LENGTH_LONG : Snackbar.LENGTH_SHORT).show ();
    }


    /**
     * 让在前台的activity,打开下一个activity
     *
     * @param intent
     */
    public void startActivity(Intent intent) {
        if (getCurrentActivity () == null) {
            BaseLog.w (TAG, "mCurrentActivity == null when startActivity(Intent)");
            //如果没有前台的activity就使用new_task模式启动activity
            intent.setFlags (Intent.FLAG_ACTIVITY_NEW_TASK);
            mApplication.startActivity (intent);
            return;
        }
        getCurrentActivity ().startActivity (intent);
    }

    /**
     * 让在前台的activity,打开下一个activity
     *
     * @param activityClass
     */
    public void startActivity(Class activityClass) {
        startActivity (new Intent (mApplication, activityClass));
    }

    /**
     * 释放资源
     */
    public void release() {
        if (EventBus.getDefault ().isRegistered (this))
            EventBus.getDefault ().unregister (this);
        mActivityList.clear ();
        mActivityList = null;
        mCurrentActivity = null;
        mApplication = null;
    }

    /**
     * 将在前台的activity保存
     *
     * @param currentActivity
     */
    public void setCurrentActivity(Activity currentActivity) {
        this.mCurrentActivity = currentActivity;
    }

    /**
     * 获得当前在前台的activity
     *
     * @return
     */
    public Activity getCurrentActivity() {
        return mCurrentActivity;
    }

    /**
     * 返回一个存储所有未销毁的activity的集合
     *
     * @return
     */
    public List<Activity> getActivityList() {
        if (mActivityList == null) {
            mActivityList = new LinkedList<> ();
        }
        return mActivityList;
    }


    /**
     * 添加Activity到集合
     */
    public void addActivity(Activity activity) {
        if (mActivityList == null) {
            mActivityList = new LinkedList<> ();
        }
        synchronized (AppManager.class) {
            if (!mActivityList.contains (activity)) {
                mActivityList.add (activity);
            }
        }
    }

    /**
     * 删除集合里的指定activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (mActivityList == null) {
            BaseLog.w (TAG, "mActivityList == null when removeActivity(Activity)");
            return;
        }
        synchronized (AppManager.class) {
            if (mActivityList.contains (activity)) {
                mActivityList.remove (activity);
            }
        }
    }

    /**
     * 删除集合里的指定位置的activity
     *
     * @param location
     */
    public Activity removeActivity(int location) {
        if (mActivityList == null) {
            BaseLog.w (TAG, "mActivityList == null when removeActivity(int)");
            return null;
        }
        synchronized (AppManager.class) {
            if (location > 0 && location < mActivityList.size ()) {
                return mActivityList.remove (location);
            }
        }
        return null;
    }

    /**
     * 关闭指定activity
     *
     * @param activityClass
     */
    public void killActivity(Class<?> activityClass) {
        if (mActivityList == null) {
            BaseLog.w (TAG, "mActivityList == null when killActivity");
            return;
        }
        for (Activity activity : mActivityList) {
            if (activity.getClass ().equals (activityClass)) {
                activity.finish ();
            }
        }
    }


    /**
     * 指定的activity实例是否存活
     *
     * @param activity
     * @return
     */
    public boolean activityInstanceIsLive(Activity activity) {
        if (mActivityList == null) {
            BaseLog.w (TAG, "mActivityList == null when activityInstanceIsLive");
            return false;
        }
        return mActivityList.contains (activity);
    }


    /**
     * 指定的activity class是否存活(一个activity可能有多个实例)
     *
     * @param activityClass
     * @return
     */
    public boolean activityClassIsLive(Class<?> activityClass) {
        if (mActivityList == null) {
            BaseLog.w (TAG, "mActivityList == null when activityClassIsLive");
            return false;
        }
        for (Activity activity : mActivityList) {
            if (activity.getClass ().equals (activityClass)) {
                return true;
            }
        }

        return false;
    }


    /**
     * 关闭所有activity
     */
    public void killAll() {
        Iterator<Activity> iterator = getActivityList ().iterator ();
        while (iterator.hasNext ()) {
            Activity next = iterator.next ();
            iterator.remove ();
            next.finish ();
        }

    }


    /**
     * 退出应用程序
     */
    public void appExit() {
        try {
            killAll ();
            if (mActivityList != null)
                mActivityList = null;
            ActivityManager activityMgr = (ActivityManager) mApplication.getSystemService (Context.ACTIVITY_SERVICE);
            //使用此方法杀死进程后，进程会重启。源码中解释如下：
            activityMgr.killBackgroundProcesses (mApplication.getPackageName ());
            System.exit (0);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }
}
